import { apiList } from './api-list.js'

const app = getApp()
export function request({key, data = {}, method = 'GET', loading = false}) {
	return new Promise((resolve, reject) => {
		if (!key) {
			uni.showToast({
				icon: 'error',
				title: '缺少请求key'
			})
			return resolve(null)
		}
		let API = apiList[key]
		if (!API) {
			uni.showToast({
				icon: 'error',
				title: '非法请求'
			})
			return resolve(null)
		}
		
		loading && uni.showLoading()
		uni.request({
			url : API,
			method,
			data,
			success(res){
				if (res.statusCode === 200) {
					let _data = res.data
					if (_data.code === 200) {}
					resolve(res.data)
				}
			},
			fail(err){
				console.log(err);
				uni.showToast({
					icon : 'none',
					title : '[0]请求服务器错误！'
				})
			},
			complete() {
				if (loading) {
					uni.hideLoading()
				}
			}
		})
	})
}

export async function MpReady() {
	if (app?.globalData?.token) {
		return true
	}
	uni.login({
		success(res) {
		},
		fail(err){
		}
	})
	let res = await request({
		key : 'login'
	})
	if (res?.code === 200) {
		app.globalData.token = res.data.token
		return true
	}
	throw '登录失败'
}